package com.ry.demo.concurrent.demo;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;


public class AtomicReferenceDemo {

    public static void main(String[] args) throws InterruptedException {

        MetaData metaData = new MetaData();
        metaData.getData().add("a");
        metaData.getData().add("b");

        AtomicReference<MetaData> atomicReference = new AtomicReference<>(metaData);


        while (true){
            MetaData currentMetaData = atomicReference.get();

            new Thread(()->{

                MetaData metaData1 = atomicReference.get();
                metaData1.getData().remove("b");
                metaData1.getData().remove("a");
                metaData1.getData().add("a");
                metaData1.getData().add("b");
                atomicReference.set(metaData1);

                System.out.println("ABA");

            }).start();

            Thread.sleep(1000);

            currentMetaData.getData().add("c");
            if (atomicReference.compareAndSet(currentMetaData,currentMetaData)){
                System.out.println("修改成功了");
                break;
            }
            System.out.println("修改失败了");
        }

        System.out.println(atomicReference.get());


    }


    @Data
    static class MetaData {
        private List<String> data = new ArrayList<>();
    }

}
